
import router from 'umi/router';
import * as commonService from 'services/commonService';
import * as sealService from 'services/sealService';
import { Modal, Toast } from 'antd-mobile';
import {
	ALIPAY_MODE,
	CERTIFICATION_TYPE,
	PERSONAL_TYPE,
	PROCESS_STATUS,
	ENTERPRISE_ACCOUNTAUTHENTICATION,
	AUTHENTICATION_TYPE_CODE,
	USER_PERMISS_USESEAL,
	USER_PERMISS_ADDSEAL
} from 'utils/Enum';
import { _arrayBufferToBase64, isDingTalk, checkAlipay } from "utils/utils"
import { returnUrl as url } from 'utils/ip';
const { alert } = Modal
export default {
	namespace: 'pdfModel',
	state: {
		useSeal: false,  //使用印章权限
		addSeal: false,  //添加印章权限
		userType: '',
		userWsid: '',
		scrollTop: 0,
		userStatus: '',//用户状态
		pdfList: [],//pdf列表
		personalIdentity: {},
		processStatus: PROCESS_STATUS.INITIAL_VALUE,
		authorName: '',//管理员姓名
		enterpriseData: {},//企业管理员基本信息
		personalObj: {
			userData: {},
			idttvStatus: '',
			userName: '',
			userIDCard: '',
			identity: {},
		},
		enterpriseObj: {
			userData: {},
			identityStatus: '',
			userName: '',
			userIDCard: '',
			idttvStatus: '',
			enterpriseStatus: '',
			enterpriseAccountAuthentication: {}
		},
		loadingAlipayPage: false,
	},
	effects: {
		*getUserSessions({ payload, callback }, { call, put }) {
			const response = yield call(commonService.getUserSessions, payload);
			if (response.code.substring(response.code.length - 4) == '0000') {
				const { session: { userWsid } } = response
				const type = userWsid.split('_')[1];
				localStorage.setItem("userWsid", userWsid);
				callback(userWsid, type)
				yield put({
					type: 'save',
					payload: { userWsid, userType: type, userStatus: 'success' }
				});
			} else {
				alert('警告', response.userMessage, [
					{ text: '返回', onPress: () => router.goBack() },
				])
				yield put({
					type: 'save',
					payload: { userStatus: 'error' }
				});
			}
			return 1

		},
		*getPersonalUsers({ payload, callback }, { call, put }) {
			const response = yield call(commonService.getPersonalUsers, payload);
			if (response.code.substring(response.code.length - 4) == '0000') {
				const { userInfo: { user: { idttvStatus } } } = response
				switch (idttvStatus) {
					case AUTHENTICATION_TYPE_CODE.PASSED:
						yield put({
							type: 'save',
							payload: {
								processStatus: PROCESS_STATUS.PUSR_AUTHORIZED_SUCCESS
							}
						})
						break;
					default:
						yield put({
							type: 'save',
							payload: {
								processStatus: PROCESS_STATUS.PUSR_AUTHORIZED_ERROR
							}
						})
						break;
				}
				yield put({
					type: 'save',
					payload: {
						personalObj: {
							userData: response.userInfo.user,
							idttvStatus: idttvStatus
						}
					}
				});

				callback()
			} else {
				alert('警告', response.userMessage, [
					{ text: '返回', onPress: () => router.goBack() },
				])
			}

		},
		*getEnterpriseUsers({ payload, callback }, { call, put }) {
			const response = yield call(commonService.getEnterpriseUsers, payload);
			if (response.code.substring(response.code.length - 4) == '0000') {
				const { enterpriseAccount: { identityStatus, enterprise: { wsid } }, enterpriseAccountAuthentication: { status } } = response;
				localStorage.setItem("enterpriseWsid", wsid);
				switch (status) {
					case ENTERPRISE_ACCOUNTAUTHENTICATION.INCOMPLETE:
						yield put({
							type: 'save',
							payload: {
								processStatus: PROCESS_STATUS.EUSR_AUTHORIZED_ERROR
							}
						})
						break;
					case ENTERPRISE_ACCOUNTAUTHENTICATION.PRIMARY_PASSED:
						switch (identityStatus) {
							case AUTHENTICATION_TYPE_CODE.PASSED:
								yield put({
									type: 'save',
									payload: {
										processStatus: PROCESS_STATUS.EPUSR_AUTHORIZED_SUCCESS
									}
								})
								break;
							default:
								yield put({
									type: 'save',
									payload: {
										processStatus: PROCESS_STATUS.EPUSR_AUTHORIZED_ERROR
									}
								})
								break;
						}

						break;
					default:
						yield put({
							type: 'save',
							payload: {
								processStatus: PROCESS_STATUS.EUSR_AUTHORIZED_ERROR
							}
						})
						break;
				}

				yield put({
					type: 'save',
					payload: {
						enterpriseObj: {
							userData: response.enterpriseAccount,
							identityStatus: identityStatus,
							enterpriseStatus: status,
							enterpriseAccountAuthentication: response.enterpriseAccountAuthentication,
						}
					}
				});
				callback()
			} else {
				Toast.hide()
				yield put({
					type: 'save',
					payload: {
						processStatus: PROCESS_STATUS.EUSR_AUTHORIZED_ERROR
					}
				})
				alert('警告', response.userMessage, [
					{ text: '返回', onPress: () => router.goBack() },
				])
			}

		},

		*getEnterpriseData({ payload }, { call, put }) {
			const response = yield call(commonService.getEnterpriseData, payload);
			if (response.code.substring(response.code.length - 4) == '0000') {
				Toast.hide();
				const { enterprise, enterprise: { authorName } } = response
				yield put({
					type: 'save',
					payload: {
						enterpriseData: enterprise,
						authorName
					}
				});
			}
			else {
				Toast.fail('企业基本信息获取失败！')
			}
		},
		*getUserPermiss({ payload, typeSeal }, { call, put }) {
			const response = yield call(commonService.getUserPermiss, payload);
			if (response.code.substring(response.code.length - 4) == '0000') {
				const { privilege: { possess } } = response
				if (typeSeal === USER_PERMISS_USESEAL) {
					yield put({
						type: 'save',
						payload: {
							useSeal: possess
						}
					});
				} else {
					yield put({
						type: 'save',
						payload: {
							addSeal: possess
						}
					});
				}
			}
			else {
				Toast.fail('权限获取失败！')
			}
		},
		*getJsapiSign({ payload, callback }, { call, put }) {
			const response = yield call(commonService.getJsapiSign, payload);
			if (response.code == 0) {
				callback(response.data)
			}
			else {
				// Toast.fail('鉴权接口请求失败！')
			}
		},
		*getSealList({ payload }, { call, put }) {
			const response = yield call(sealService.getSealList, payload);
			if (response.code.substring(response.code.length - 4) == '0000') {
				yield put({
					type: 'save',
					payload: {
						sealList: response
					}
				});
			}
			else {
				Toast.fail('获取印章列表失败')
			}
		},
		*getPDFList({ payload }, { call, put }) {
			const response = yield call(commonService.getPDFList, payload);
			if (response.code.substring(response.code.length - 4) == '0000') {
				const { contents } = response;
				yield put({
					type: 'save',
					payload: {
						pdfList: contents
					}
				});
			} else {
				Toast.fail("文件获取失败！", 2)
			}
		},
		*getPDFDetail({ payload }, { call, put }) {
			const response = yield call(commonService.getPDFDetail, payload);
			if (response.code.substring(response.code.length - 4) == '0000') {
				const file = _arrayBufferToBase64(response.resultData)
				yield put({
					type: 'save',
					payload: {
						pdfBase64: file
					}
				});
			}
			else {
				Toast.fail("获取pdf详情失败")
			}

		},
		*getIntendCertification({ payload }, { call, put }) {
			const response = yield call(commonService.getIntendCertification, payload);
			if (response.code.substring(response.code.length - 4) == '0000') {
				const { alipayCertificateUrl } = response;
				// checkAlipay(`alipays://platformapi/startapp?appId=20000067&url=${escape(alipayCertificateUrl)}`)
				window.location.href = `alipays://platformapi/startapp?appId=20000067&url=${escape(alipayCertificateUrl)}`
				Toast.hide()
			} else {
				put({
					type: 'save',
					payload: {
						loadingAlipayPage: false,
					}
				})
				Toast.fail('意愿认证失败！')
			}
		},

		*getIntendPersonData({ payload }, { call, put }) {
			const response = yield call(commonService.getPersonData, payload.id);
			if (response.code.substring(response.code.length - 4) == '0000') {
				const session = localStorage.getItem('Session');
				const userWsid = localStorage.getItem('userWsid');
				const returnUrl = localStorage.getItem('returnUrl');
				const envelopeWsid = localStorage.getItem('envelopeWsid');
				const participantWsid = localStorage.getItem('participantWsid');
				const enterType = localStorage.getItem('enterType');
				let { identity: { info = '' } } = response;
				if (!info) {
					info = { name: '', idCardNo: '' };
				}
				const haveToAlipay = 'yes';
				let alipayReturnUrl = `${url()}/SignCertificationResults?envelopeWsid=${envelopeWsid}&participantWsid=${participantWsid}&type=${payload.userType}&userWsid=${userWsid}&session=${session}&Certification=${PROCESS_STATUS.UNKOWN_WISH_APPLY}&returnUrl=${escape(returnUrl)}&enterType=${enterType}&haveToAlipay=${haveToAlipay}`;
				if (isDingTalk()) {
					alipayReturnUrl = `dingtalk://dingtalkclient/page/link?url=${escape(alipayReturnUrl)}`;
				}
				const { name, idCardNo } = info;
				yield put({
					type: 'getIntendCertification',
					payload: {
						certName: name,
						certNo: idCardNo,
						faceType: ALIPAY_MODE.MULTIPLE_FACTOR,
						userPersonWsid: userWsid,
						returnUrl: alipayReturnUrl,

					},
				});
				yield put({
					type: 'save',
					payload: {
						userName: name,
						userIDCard: idCardNo,
					},
				});
			} else {
				// Toast.fail('获取个人信息失败！');
			}
		},
		*getPersonData({ payload }, { call, put }) {
			const response = yield call(commonService.getPersonData, payload.id);
			if (response.code.substring(response.code.length - 4) == '0000') {
				const { identity: { info: { name, idCardNo } } } = response;
				yield put({
					type: 'save',
					payload: {
						personalIdentity: response.identity.info
					}
				});
				yield put({
					type: 'save',
					payload: {
						userName: name,
						userIDCard: idCardNo
					}
				});
			}
			else {
				Toast.fail("获取个人认证信息失败！")
			}
		},
	},
	reducers: {
		save(state, { payload }) {
			return {
				...state,
				...payload,
			}
		}
	},

};
